const {Project} = require('../../mongodb/models')
const {getUserByCtx} = require('../../utils/common')

module.exports = [
	{
		path: '/project',
		method: 'post',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			var projectIsExist = await Project.findOne({name: ctx.request.body.name, userId: _id}, (err, doc)=>doc)
			if(projectIsExist){
				ctx.response.body = {
					errCode: 1,
					errMsg: '项目已存在'
				}
			}else{
				var doc = await Project.create({name: ctx.request.body.name, userId: _id})
				ctx.response.body = {
					errCode: doc ? 0 : -1,
					errMsg: doc ? '创建成功' : '创建失败',
					data: doc
				}
			}
		}
	},{
		path: '/project',
		method: 'get',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			var docs = await Project.find({userId: _id}, (err, docs)=>docs)
			ctx.response.body = {
				errCode: docs ? 0 : -1,
				errMsg: docs ? 'request:success' : '项目获取失败',
				data: docs
			}
		},
	},{
		path: '/project/:id',
		method: 'delete',
		process: async (ctx, next) => {
			const {_id} = getUserByCtx(ctx)
			var doc = await Project.deleteOne({_id:ctx.params.id, userId: _id}, (err,doc)=>doc)
			ctx.response.body = {
				errCode: doc ? 0 : -1,
				errMsg: doc ? '删除成功' : '删除失败',
				data: doc
			}
		}
	},{
		path: '/projectInfo',
		method: 'get',
		process: async (ctx, next) => {
			var doc = await Project.findById(ctx.query.id)
			ctx.response.body = {
				errCode: doc ? 0 : -1,
				errMsg: doc ? 'request:success' : '项目信息获取失败',
				data: doc ? {
					name: doc.name,
					_id: doc._id
				} : {}
			}
		}
	}
]